﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkitMvvmDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommunityToolkitMvvmDemo.ViewModels
{
    public partial class StudentFormViewModel : ObservableRecipient, IRecipient<ValueChangedMessage<bool>>
    {
        [ObservableProperty] // 自动生成Name
        [NotifyPropertyChangedRecipients] // 当属性变化时，会调用 Broadcast 方法
        private string name;

        [ObservableProperty] // 自动生成Class
        [NotifyPropertyChangedRecipients]
        private int _age;

        [ObservableProperty] // // 自动生成Phone
        [NotifyPropertyChangedRecipients]
        private string phone;

        public string SqlQuery => $"INSERT INTO Students (Name, Age, Phone) VALUES ('{Name}', '{Age}', '{Phone}')";

        private bool allowAddNew;
        private bool CanAddNew() => allowAddNew;  // 控制按钮是否能点击
        [RelayCommand(CanExecute = nameof(CanAddNew))]  // 会生成 AddNewCommand
        private void AddNew()
        {
            // 发送学生消息
            //WeakReferenceMessenger.Default.Send(new ValueChangedMessage<Student>(new Student(Name, Age, Phone)));
            WeakReferenceMessenger.Default.Send(new ValueChangedMessage<Student>(new Student() { Name=name,Age=Age,Phone=phone}));
        }

        public void Receive(ValueChangedMessage<bool> message)
        {
            allowAddNew = message.Value;
            AddNewCommand.NotifyCanExecuteChanged();  // 通知 CanExecute  property 已经改变了
        }
    }
}
